from django.db import models
from django.db.models import signals
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType

class TimeLine(models.Model):
    project = models.ForeignKey('projects.Project', editable=False)
    description = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

    def __unicode__(self):
        return self.description

    class Meta:
        ordering = ('-date',)

def timeline_updater(sender, **kwargs):
    instance = kwargs['instance']
    project = instance.project
    if 'created' in kwargs and kwargs['created']:
        msg = 'Created '
    else:
        msg = 'Updated '
    TimeLine.objects.create(project=project,
                            description=msg + sender.__name__,
                            content_object=instance)

class Milestone(models.Model):
    project = models.ForeignKey('projects.Project', editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    date_due = models.DateTimeField(null=True, blank=True)
    date_completed = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-date_due',]

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('milestone_detail', [self.project.slug, str(self.id)])

# Signals
signals.post_save.connect(timeline_updater, sender=Milestone)